﻿<?php
// 本类由系统自动生成，仅供测试用途
class IndexAction extends Action
{
    public $mGoods;
    public $mGoodsCategory;
    public function _initialize()
    {
        $this->mGoods = D('Base/RestaurantstyyGoods');
        $this->mGoodsCategory = D('Base/RestaurantstyyGoodsCategory');
        $this->mWindow = D('Base/RestaurantstyyWindow');
    }

    public function index()
    {
        $this->show('<style type="text/css">*{ padding: 0; margin: 0; } div{ padding: 4px 48px;} body{ background: #fff; font-family: "微软雅黑"; color: #333;} h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; } p{ line-height: 1.8em; font-size: 36px }</style><div style="padding: 24px 48px;"> <h1>:)</h1><p>欢迎使用 <b>ThinkPHP</b>！</p></div><script type="text/javascript" src="http://tajs.qq.com/stats?sId=9347272" charset="UTF-8"></script>', 'utf-8');
    }

    /**
     * http请求
     * @param $url 请求地址
     * @param null $postFields 请求参数
     * @return mixed
     * @throws Exception
     */
    public function curl($url = '', $postParams= null)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT,30);
        curl_setopt($ch, CURLOPT_HEADER,0);
        // post提交数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // post的变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postParams);
        if(!is_array($postParams)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($postParams)
            ));
        }
        $output = json_decode(curl_exec($ch),true);

        curl_close($ch);
        //打印获得的数据
        return $output;
    }


    public function curl1($url = ''){

            $curl = curl_init();
            curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
            curl_setopt($curl,CURLOPT_URL, $url);
            curl_setopt($curl,CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
            $resp = curl_exec($curl);
            curl_close($curl);
            return $resp;

    }


    /**
     * 获取微信点餐的队列信息
     */
    public function doPrint1()
    {
        for ($i = 1; $i < 30; $i++) {
            $this->getPrint();
            sleep(2);
        }
    }

    /**
     * 存微信订单信息
     */
    public function getPrint()
    {
        $data=file_get_contents('http://10.203.7.44/Restaurantstyy/ZduRestaurantApi/getorder');
        $num = strpos($data,'{');
        $num1 = strrpos($data,'}');
        $data = substr($data,$num,$num1);
        $data = json_decode($data,true);

        if ($data['code'] == 200) {
            $redis = RedisQueueService::getInstance();
            $redis->push('styy_print', $data['data']);
        }
    }
    function test(){
    
    
    }

    /***
     * 获取队列 打印订餐
     */
    public function doPrint2()
    {
        import("@.ORG.RedisService");
        //实例化redis服务
        import("@.ORG.RedisService");

        $redis = RedisQueueService::getInstance();
        $data = $redis->pull('styy_print_1');
        //p($data);
        var_dump($data);exit;
    }
    /**
     * 保存点餐机发送过来的订单信息
     */
     /**
     * 保存点餐机发送过来的订单信息
     */
    public function addPrint()
    {

        $data = $GLOBALS['HTTP_RAW_POST_DATA'];

        import("@.ORG.RedisService");
        $post = json_decode($data, true);
        wLog(date("Y-m-d H:i:s")." addPrint-post ".var_export($post,true),"notify");
        $post = json_decode($post['print'], true);

        //实例化redis服务
        $redis = RedisQueueService::getInstance();

        $printInfo = array('order_sn' => $post['order_sn'], 'order_num' => $post['order_num'], 'order_amount' => $post['order_amount'], 'pay_type' => $post['pay_type'], 'restaurant' => $post['restaurant'],
            'push_time' => time(), 'goods' => $post['goods'],'goods_amount'=>$post['goods_amount'],'discount_amount'=>$post['discount_amount']);

        $order_sn=$printInfo['order_sn'];

	      wLog(date('Y-m-d H:i:s') . 'order_sn: '. $order_sn, 'styy2'); 
       if(!RedisService::keyExists( $order_sn)){
            RedisService::set($order_sn,  $order_sn,3600);
        }else{
            return false;
        }
	
        $redis->push('styy_print_1', $printInfo);
           $c= $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].(json_encode($printInfo));
	      wLog(date('Y-m-d H:i:s') . 'printInfo2: '. $c, 'styy2');  
	      

         $redis->push('styy_print_1', $printInfo);
   //     $datas = $redis->pull('styy_print_1');
//        p($datas);
  //      die('1112');

         $this->ajaxReturn(array('code' => 200, 'message' => '请求成功', 'data' => array()));

        /* $order = json_decode($post['print'], true);
         //实例化redis服务
         $redis = RedisQueueService::getInstance();
         $hotGoods = array();
         $coldGoods = array();
         $waterGoods = array();
         if (count($order) == 0) {
             $this->ajaxReturn(array('code' => 10086, 'message' => '数据为空', 'data' => array()));
         }
         foreach ($order['goods_list'] as $k => $v) {
             if ($v['print_type'] == 1) {
                 $hotGoods[] = $v;
             } elseif ($v['print_type'] == 2) {
                 $coldGoods[] = $v;
             } elseif ($v['print_type'] == 3) {
                 $waterGoods[] = $v;
             }
         }
         $printInfo = array('order_sn' => $order['order_sn'], 'order_num' => $order['order_num'], 'order_amount' => $order['order_amount'], 'pay_type' => $order['pay_type'], 'restaurant' => $order['restaurant'],
             'push_time' => time(), 'hot_list' => $hotGoods, 'cold_list' => $coldGoods, 'water_list' => $waterGoods);
	   $c= $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].(json_encode($_POST));
	   
         $redis->push('styy_print_1', $printInfo);
	 
	     wLog(date('Y-m-d H:i:s') . 'printInfo': ' . $printInfo, 'styy2');
         $this->ajaxReturn(array('code' => 200, 'message' => '请求成功', 'data' => array()));*/
    }

    /***
     * 获取队列 打印订餐
     */
    public function doPrint()
    {
        for ($i = 1; $i < 30; $i++) {
	 wLog(date('Y-m-d H:i:s') . 'nums: ' . "123456", 'styy3');
            $this->toPrint();
            sleep(2);
        }
    }

    //得到redis的兼职


   public function  test2(){
      $redis = RedisQueueService::getInstance();
       $data = $redis->pull('styy_print_1');
       $len=strlen($data);
       var_dump($len);
  }


  /**
     *定时的在队列中获取打印信息
     */
    public function toPrint()
    {

        //实例化redis服务
        $redis = RedisQueueService::getInstance();
        $data = $redis->pull('styy_print_1');
	
        $dataold = $data;
        wLog(date("Y-m-d H:i:s")." addPrint-data ".var_export($data,true),"notify1");
        $type = $data['pay_type'];
        $payType = '';

        //档口id
        $windids = $this->mWindow->where(array('cut_off'=>0))->getField('window_id',true);

        $data = $this->updateOrder($data);

        if (!$data) {
            return true;
        }

        if ($type == 1) {
            $payType = '微信';
        }else if($type == 5){
            $payType = '支付宝';
        }else if($type == 4 || 6){
            $payType = '校园卡';
        }



        //档口对应的打印机id
        $list = C('list');  // 在/home/wwwroot/print.com/print/BEESCRMdata/conf/info.php文件

        foreach($windids as $k=>$v){
	       wLog(date("Y-m-d H:i:s")." windowid :"."true","styy3");
	       $dataww=json_encode($data);
	      wLog(date("Y-m-d H:i:s")."dataww:".$dataww,"styy3");
            if (count($data['goods'][$v]) > 0) {
                $service_port = 9100;
                $address = '192.168.1.146';
	
                if($list[$v]){
                    $address = $list[$v];
                }
		    wLog(date("Y-m-d H:i:s")." goods :"."true","styy3");
                $content = $this->content($data, $payType, $type = $v);

                //如果是小炒档口，连续打印四张
                if($address == '192.168.1.148'){
                    for($i=0;$i<4;$i++){
                        $this->Send_socket_connect($service_port, $address, $content, $type = 'hot_list', $data,$dataold);
                        sleep(0.5);
                    }
                }elseif($address == '192.168.1.149'){//鲁儿饭 档口50，打印两个打印机
                        $this->Send_socket_connect($service_port, $address, $content, $type = 'hot_list', $data,$dataold);
                        sleep(0.5);
                        $address = '192.168.1.201';
				    wLog(date("Y-m-d H:i:s")." 147 :"."true","styy3");
                        $this->Send_socket_connect($service_port, $address, $content, $type = 'hot_list', $data,$dataold);
                }else{
                    $this->Send_socket_connect($service_port, $address, $content, $type = 'hot_list', $data,$dataold);
                }
            }
        }
//        foreach($windids as $k=>$v){
//            if (count($data['goods'][$v]) > 0) {
//                $service_port = 9100;
//                $address = '192.168.1.111';
//                if($list[$v]){
//                    $address = explode(',',$list[$v]);
//                }
//                $content = $this->content($data, $payType, $type = $v);
//                //如果是小炒档口，连续打印四张
//                if(in_array('10.211.11.139',$address){
//                    for($i=0;$i<4;$i++){
//                        foreach($address as $k=>$v){
//                            $this->Send_socket_connect($service_port, $v, $content, $type = 'hot_list', $data);
//                        }
//                        sleep(0.5);
//                    }
//            }else{
//                    foreach($address as $k=>$v){
//                        $this->Send_socket_connect($service_port, $v, $content, $type = 'hot_list', $data);
//                    }
//
//                }
//            }
//        }
//        if (count($data['goods']['6']) > 0) {
//            $service_port = 9100;
//            $address = '192.168.1.111';
//            $content = $this->content($data, $payType, $type = '6');
//            $this->Send_socket_connect($service_port, $address, $content, $type = 'hot_list', $data);
//        }
    }


    /*
     *拼接数据
     */
    private function content($data,$payType,$type)
    {
        $htotal = 0;
        $hstr = '';
        $name = '';
        $list1 = array('49', '52', '56'); //1楼
        $list2 = array('50', '51', '53', '57'); //2楼
        if (in_array($type, $list1)) {
            $name = '麦思威';
        } elseif (in_array($type, $list2)) {
            $name = '浙大饮食';
        } else {
            $name = '浙大二食堂';
        }
        $table = $data['tableno_id'] ? $data['tableno_id'] : 1;
        //添加包含西餐和料理的判断
//        if (isset($data['goods']['49']) && isset($data['goods']['56'])) {
//            foreach ($data['goods']['49'] as $hk => $hv) {
//                $hstr .= str_pad($hv['goods_name'], 36, '　') . ' ' . str_pad($hv['goods_num'], 16, '　') . '￥' . number_format($hv['goods_num'] * $hv['goods_price'], 2) . "\x0D\x0A" . "\x0D\x0A";
//                $htotal += $hv['goods_num'] * $hv['goods_price'];
//            }
//
//            foreach ($data['goods']['56'] as $hk => $hv) {
//                $hstr .= str_pad($hv['goods_name'], 36, '　') . ' ' . str_pad($hv['goods_num'], 16, '　') . '￥' . number_format($hv['goods_num'] * $hv['goods_price'], 2) . "\x0D\x0A" . "\x0D\x0A";
//                $htotal += $hv['goods_num'] * $hv['goods_price'];
//            }
//
//        } else {
//            foreach ($data['goods'][$type] as $hk => $hv) {
//                $hstr .= str_pad($hv['goods_name'], 36, '　') . ' ' . str_pad($hv['goods_num'], 16, '　') . '￥' . number_format($hv['goods_num'] * $hv['goods_price'], 2) . "\x0D\x0A" . "\x0D\x0A";
//                $htotal += $hv['goods_num'] * $hv['goods_price'];
//            }
//        }

        foreach ($data['goods'][$type] as $hk => $hv) {
            $hstr .= str_pad($hv['goods_name'], 36, '　') . ' ' . str_pad($hv['goods_num'], 16, '　') . '￥' . number_format($hv['goods_num'] * $hv['goods_price'], 2) . "\x0D\x0A" . "\x0D\x0A";
            $htotal += $hv['goods_num'] * $hv['goods_price'];
        }

        $content =
            "\x1B\x21\x08\x1B\x21\x10" . '                 ' . $name . "\x0A\x0A" .
            '餐号：' . $data['order_num'] . "\x0A" . ' ' . "\x0A" .
            '桌号：' . $table . "\x0A" . ' ' . "\x0A" .
            "\x1B\x21\x00" . '订单编号：' . $data['order_sn'] . "\x0A" . ' ' . "\x0A" .
            '打印时间:' . date("Y-m-d H:i:s") . "\x0A" . ' ' . "\x0A" .
            '支付方式:' . $payType . "\x0A" . ' ' . "\x0A" .
            '------------------------------------------------' . "\x0A" . ' ' . "\x0A" .
            "\x1B\x21\x08\x1B\x21\x10" . str_pad('商品名称', 36, '　') . str_pad('数量', 15) . '小计' . "\x0A" . ' ' . "\x0A" . $hstr . "\x0A" .
            '------------------------------------------------' .

            "\x0A" . '合计：' . $htotal . '元' . ' ' . '优惠：' . $data['discount_amount'] . '元' . '实付：' . $data['goods_amount'] . '元' ."\x0A" . ' ' . "\x0A" . "\x1B\x21\x08\x1B\x21\x10" .'              ' . '青橄榄网络技术支持' . ' ' . "\x0A" . ' ' . "\x0A" . ' ' . "\x0A" . ' ' . "\x0A" . '  ' . "\x0A\x1D\x56\x01";
        return $content;
    }

    /**
     *本地打印
     *
     */
    public function Send_socket_connect($service_port, $address, $in, $type, $data,$dataold)
    {
        //创建 TCP/IP socket$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("could not create socket!");
        $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("could not create socket!");
        //设置超时时间
        $timeout = 2;
	   wLog(date("Y-m-d H:i:s")." err7"."hhhhh","styy3");
        $time = time();
        //设置非阻塞模式
        // @socket_set_nonblock($socket);
        /*$comand="\x1D\x56\x01\x48";
        $in=$in.$comand;*/
        $in = mb_convert_encoding($in, "GBK", "UTF-8");
		   wLog(date("Y-m-d H:i:s")." err"."1234567","styy3");
       
        //超时判断
        while (!@socket_connect($socket, $address, $service_port)) {
	   wLog(date("Y-m-d H:i:s")." err2"."345","styy3");
            $err = socket_last_error($socket);
	          wLog(date("Y-m-d H:i:s")." err_num :".$err,"styy3");
            // 连接成功，跳出循环
            if ($err === 10056) {
                break;
            }
	    
	    
            //连接失败，判断超时时间，停止
            if ((time() - $time) >= $timeout) {
                socket_close($socket);
                print('网络异常，请检查网络连接！！');

                $redis = RedisQueueService::getInstance();
		   wLog(date("Y-m-d H:i:s")." errtype".$type,"styy3");
                if ($type == 'hot_list') {
		wLog(date("Y-m-d H:i:s")." pull-in"."yes","styy3");
		$redis->push('styy_print_1',$dataold, $pushType = 'tail');
	
		
                }
                exit();
            }
            // 刷新频率（250毫秒）
            //usleep(250000);
        }
        //设置阻塞模式
        @socket_set_block($socket);
        //发送命令到设备
        socket_write($socket, $in, strlen($in));
        //关闭连接
        socket_close($socket);
    }
    

public function test3(){
  $timeout = 2;
  $time = time();
  sleep(2);
 //连接失败，判断超时时间，停止
            if ((time() - $time) >= $timeout) {
                socket_close($socket);
                print('网络异常，请检查网络连接！！');
		$data="1234";

                $redis = RedisQueueService::getInstance();
                //if ($type == 'hot_list') {
                    $redis->push('styy_print_1', $data, $pushType = 'tail');
		               $datas=$redis->pull('styy_print_1');
			       var_dump($datas);
               // }
                exit();
            }

}

    public function runAll()
    {
        set_time_limit(0);
        while (1) {
            $this->getPrint();
            $this->toPrint();
            sleep(1);
        }
    }

    /*
     * curlGet请求
     */
    public function curlToGet($url)
    {
        //初始化
        $ch = curl_init();
        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //执行并获取HTML文档内容
        $output = curl_exec($ch);

        //打印获得的数据
        //释放curl句柄
        curl_close($ch);

        return json_decode($output, true);
    }


    public function updateOrder($data){
        //查询订单信息
        $goods = array();
        $categoryIds = $this->mGoods->where(array('cut_off'=>0))->getField('goods_id,category_id');
        $windowIds = $this->mGoodsCategory->where(array('cut_off'=>0))->getField('category_id,window_id');

        foreach($data['goods'] as $k=>$v) {
            $goods[$windowIds[$categoryIds[$v['goods_id']]]][] = $v;
        }
        $data['goods'] = $goods;
        return $data;
    }
}